﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Dependency;
using Abp.Events.Bus.Exceptions;
using Abp.Events.Bus.Handlers;
using Abp.UI;
using Abp.Web.Mvc.Authorization;
using WanFang.Authorization;
using WanFang.Authorization.Roles;
using WanFang.Users;
using WanFang.Web.Models.Users;
using WanFang.Authorization.Users;
using WanFang.Web.Models.Account;
using Abp.Extensions;
using Microsoft.AspNet.Identity;
using Abp.Domain.Uow;
using Abp.Authorization.Users;
using System.Collections.Generic;
using WanFang.Test;
using Abp.Organizations;
using System.Text;
using WanFang.Users.Dto;
using AutoMapper;

namespace WanFang.Web.Controllers
{
    [AbpMvcAuthorize]
    public class TestOrganizationController : WanFangControllerBase
    {
        private readonly IUserAppService _userAppService;
        private readonly RoleManager _roleManager;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly UserManager _userManager;
        private readonly OrganizationUnitManager _organizationUnitManager;

        public TestOrganizationController(IUserAppService userAppService, RoleManager roleManager,
            IUnitOfWorkManager unitOfWorkManager,
            UserManager userManager,
            OrganizationUnitManager organizationUnitManager)
        {
            _userAppService = userAppService;
            _roleManager = roleManager;
            _unitOfWorkManager = unitOfWorkManager;
            _userManager = userManager;
            _organizationUnitManager = organizationUnitManager;
        }

        public async Task<ActionResult> List()
        {
            var lst = await _organizationUnitManager.FindChildrenAsync(null);
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for (int i = 0; i < lst.Count; i++)
            {
                OrganizationUnit ou = lst[i];
                if (i > 0)
                {
                    sb.Append(",");
                }
                sb.Append("{");
                sb.AppendFormat("'text':'{0}'", ou.DisplayName);
                sb.AppendFormat(",'id':'{0}'", ou.Id);
                sb.Append("}");
            }
            sb.Append("]");
            ViewBag.ou = sb.ToString();
            return View();
        }
        [HttpPost]
        public ActionResult List(FormCollection frm)
        {
            var lst = _organizationUnitManager.FindChildren(null);
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for(int i=0;i<lst.Count;i++)
            {
                OrganizationUnit ou = lst[i];
                if (i > 0)
                {
                    sb.Append(",");
                }
                sb.Append("{");
                sb.AppendFormat("'text':'{0}'", ou.DisplayName);
                sb.AppendFormat(",'id':'{0}'", ou.Id);
                sb.Append("}");
            }
            sb.Append("]");
            return Content(sb.ToString());
        }
        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        public async Task<ActionResult> OuPersonList(int id)
        {
            using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant, AbpDataFilters.MustHaveTenant))
            {
                var lst = await _userManager.GetUsersInOrganizationUnit(new OrganizationUnit { Id = id });
            var userLst = Mapper.Map<List<UserDto>>(lst);
            return AbpJson(userLst,null,null, JsonRequestBehavior.AllowGet,false,false);
            }
        }

        public ActionResult PersonList()
        {
            using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant, AbpDataFilters.MustHaveTenant))
            {
                var lst = _userManager.Users.ToList();
                var userLst = Mapper.Map<List<UserDto>>(lst);
                return View(userLst);
            }
        }
        [HttpPost]
        public ActionResult SetOu(int id,int ouId)
        {
            _userManager.SetOrganizationUnitsAsync(id, ouId);
            return Json(new ResultMsg());
        }
        [HttpPost]
        public ActionResult Add(string DisplayName)
        {
           
               var orz = new OrganizationUnit
            {
                Code = _organizationUnitManager.GetNextChildCode(null),
                DisplayName = DisplayName
            };
            _organizationUnitManager.Create(orz);
            return Json(new ResultMsg());
        }

        public async Task<ActionResult> Update()
        {
            var user = await _userManager.GetUserByIdAsync(AbpSession.UserId.Value);
            var model = new RegisterViewModel
            {
                Name = user.Name,
                Surname = user.Surname,
                EmailAddress = user.EmailAddress,
                UserName=user.UserName
            };
            return View(model);
        }
        [HttpPost]
        public ActionResult Update(RegisterViewModel model)
        {
            if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
            {
                throw new UserFriendlyException(L("FormIsNotValidMessage"));
            }
            var user = new User
            {
                Name = model.Name,
                Surname = model.Surname,
                EmailAddress = model.EmailAddress,
                IsActive = true
            };
            user.UserName = model.UserName;
            user.Password = new PasswordHasher().HashPassword(model.Password);
            user.Roles = new List<UserRole>();
            foreach (var defaultRole in _roleManager.Roles.Where(r => r.IsDefault).ToList())
            {
                user.Roles.Add(new UserRole { RoleId = defaultRole.Id });
            }
            user.Id = AbpSession.UserId.Value;
            _userManager.Update(user);
            return Json(new ResultMsg());
        }
    }
}